//
//  NSFileHandleViewController.m
//  StudyDemo
//
//  Created by 赵忠鹏 on 2018/5/4.
//  Copyright © 2018年 zhaozhongpeng. All rights reserved.
//

#import "NSFileHandleViewController.h"

@interface NSFileHandleViewController ()<NSURLConnectionDataDelegate>

@property (weak, nonatomic) IBOutlet UITextView *showPathTextView;


@property (weak, nonatomic) IBOutlet UIProgressView *handleProgess;

@property (nonatomic,assign) CGFloat totalLength;

@property (nonatomic,copy) NSString *fileName;

@property (nonatomic,copy) NSString *filePath;

@property (nonatomic,strong) NSFileHandle *handle;

@property (nonatomic,assign) CGFloat currentLength;

@end

@implementation NSFileHandleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    self.totalLength = response.expectedContentLength; // 文件总大下
    
    self.fileName = response.suggestedFilename; // 服务器推荐名字
    
    // 创建一个新的文件，存数据
    // 1.获取文件管理者
    NSFileManager *manager = [NSFileManager defaultManager];
    
    // 2.拼接文件全路径
    self.filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:self.fileName];
    self.showPathTextView.text = self.filePath;
    NSLog(@" 路径 - %@",self.filePath);
    // 3.创建一个空的文件
    [manager createFileAtPath:self.filePath contents:nil attributes:nil];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    self.currentLength += data.length;
    
    // 创建文件句柄用来写数据
    // 1.当文件下载完句柄 需要关闭，closeFile 方法
     self.handle = [NSFileHandle fileHandleForWritingAtPath:self.filePath];
    
    // 2.设置写数据的文字
    [self.handle seekToEndOfFile];
    
    // 3.写数据
    [self.handle writeData:data];
    
    
    self.handleProgess.progress = 1.0 * (self.currentLength/self.totalLength);
    
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [self.handle closeFile];
    self.handle = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self.handle closeFile];
    self.handle = nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
